define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    let current_kind = 'all';
    let selectedValue = [];
    $('#c-parent_id').change(function () {
        var qid = $(this).val();
        // console.log(qid);return;
        $.ajax({
            url:"exam/tiku/son_cate",
            method: 'post',
            data: { 'qid': qid },
            success:function(data) {

                if(data.code == 100)
                {
                    var html = `<option value="0" selected>无</option>`;
                    var list = data.list;

                    for (var j = 0; j < list.length; j++)
                    {
                        html += `<option value="` + list[j].id + `">` + list[j].name + `</option>`;
                    }
                    // console.log(html);
                    $('#c-parent_id_t').html(html);
                }
                else if(data.code == 1)
                {
                    var html = `<option value="0" selected>无</option>`;
                    $('#c-parent_id_t').html(html);
                }
            },
            error: function(err) {
                console.log("失败了: " + err);
            }
        });
    });

    //复制分类
    let isSuccess = false;
    $(document).on('click', '.btn-copycate', function() {
        var ids = selectedValue.map((item) => {
            console.log(item);
            return item.id;
        });
        if (isSuccess) {
            Layer.open({
                title:'提示',
                content:'数据提交中....'
            });
            return ;
        }
        isSuccess = true;

        Layer.open({
            title:'提示',
            content:'数据提交中....'
        });
        $.ajax({
            url:"exam/tiku/copycate",
            method: 'post',
            data: { 'ids': ids.join(',') },
            success:function(data) {

                if(data.code == 1) {
                    Layer.open({
                        title:'提示',
                        content:'复制成功'
                    });
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    Layer.open({
                        title:'提示',
                        content: data.msg
                    });
                }
            },
            error: function(err) {
                console.log("失败了: " + err);
            }
        });
    });
    
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'exam/tiku/index' + location.search,
                    add_url: 'exam/tiku/add?kind=' + current_kind,
                    edit_url: 'exam/tiku/edit',
                    del_url: 'exam/tiku/del_all',
                    multi_url: 'exam/tiku/multi',
                    import_url: 'exam/tiku/import',
                    table: 'exam_cate',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                pagination: false,
                commonSearch: false,
                search: false,
                showExport: false,//隐藏导出
                showToggle: false,//隐藏浏览模式
                showColumns: false,//隐藏显示隐藏模式
                searchFormVisible: true,//默认显示搜索表单
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {
                            field: 'name', title: __('Name'), operate: false, align: 'left', formatter:function (value, row, index) {
                                return value.toString().replace(/(&|&amp;)nbsp;/g, '&nbsp;');
                            }},
                        {
                            field: 'kind',
                            title: __('Kind'),
                            searchList: {"QUESTION": __('Question'), "PAPER": __('Paper'), "ROOM": __('Room')},
                            formatter: Table.api.formatter.normal
                        },
                        // {
                        //     field: 'uses',
                        //     title: __('uses'),
                        //     searchList: {"ONLY_MEMBER": __('ONLY_MEMBER'),"ALL": __('ALL'),},
                        //     formatter: function (value, row, index) {
                        //         if (row.kind == 'QUESTION') {
                        //             return Table.api.formatter.status(value, row, index);
                        //         }
                        //         return '-';
                        //     }
                        // },
                        // {field: 'icon', title: __('Icon'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        // {field: 'parent_id', title: __('Parent_id'), operate: 'LIKE'},
                        {field: 'sort', title: __('Sort')},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                             buttons: [
                                
                                /*{
                                    name: 'detail',
                                    title: __('弹出窗口打开'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'example/bootstraptable/detail',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },*/
                                {
                                    name: 'cate',
                                    title: __('分类'),
                                    text: __('分类'),
                                    extend:'data-area=["90%","90%"]',
                                    classname: 'btn btn-xs btn-primary btn-dialog btncsa',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'exam/tiku?parent_id=' + row.id
                                    },
                                    visible:function(row){
                                        // console.log(row);
                                        if(row.level == 1)
                                        {
                                            return true;
                                        }
                                    },
                                },
                                {
                                    name: 'tiku_question',
                                    title: __('查看试题'),
                                     text: __('查看试题'),
                                    extend:'data-area=["90%","90%"]',
                                    classname: 'btn  btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-list',
                                    url: function (row) {
                                        return 'exam/tiku_question?cate_id=' + row.id
                                    },
                                    // visible:function(row){
                                    //     // console.log(row);
                                    //     if(row.level == 1)
                                    //     {
                                    //         return true;
                                    //     }
                                    // },
                                },
                                // {
                                //     name: 'allocation',
                                //     title: __('题库编辑'),
                                //      text: __('题库编辑'),
                                //     extend:'data-area=["95%","95%"]',
                                //     classname: 'btn  btn-xs btn-warning btn-dialog',
                                //     icon: 'fa fa-list',
                                //     url: function (row) {
                                //         return 'exam/question/allocation?cate_id=' + row.id
                                //     },
                                //     // visible:function(row){
                                //     //     // console.log(row);
                                //     //     if(row.level == 1)
                                //     //     {
                                //     //         return true;
                                //     //     }
                                //     // },
                                // },
                                // {
                                //     name: 'allocation',
                                //     title: __('试题导入'),
                                //      text: __('试题导入'),
                                //     extend:'data-area=["40%","60%"]',
                                //     classname: 'btn  btn-xs btn-danger  btn-dialog',
                                //     icon: 'fa fa-list',
                                //     url: function (row) {
                                //         return 'exam/question/import?cate_id=' + row.id
                                //     },
                                //     // visible:function(row){
                                //     //     // console.log(row);
                                //     //     if(row.level == 1)
                                //     //     {
                                //     //         return true;
                                //     //     }
                                //     // },
                                // },
                                //  {
                                //      name: 'expandlink',
                                //      title: __('拓展链接'),
                                //      text: __('拓展链接'),
                                //      extend:'data-area=["30%","40%"]',
                                //      classname: 'btn  btn-xs btn-info btn-dialog',
                                //      icon: 'fa fa-list',
                                //      url: function (row) {
                                //          return 'exam/tiku/expandlink?id=' + row.id;
                                //      },
                                //      visible:function(row){
                                //          // console.log(row);
                                //          if(row.level == 4)
                                //          {
                                //              return true;
                                //          }
                                //      },
                                //  }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
                //点击全选框时触发的操作        
                onCheckAll:function(row){ 
                    Controller.api.bindevent();
                    selectedValue= $("#table").bootstrapTable('getSelections');
                    console.log(selectedValue);
                },
                //取消所有
                onUncheckAll: function (row) {
                    Controller.api.bindevent();
                    selectedValue= $("#table").bootstrapTable('getSelections'); 
                    console.log(selectedValue);
                },
                //点击行前面的选择框
                onCheck:function(row,$element){
                    Controller.api.bindevent();
                    selectedValue= $("#table").bootstrapTable('getSelections'); 
                    console.log(selectedValue);
                },
                //取消选中
                onUncheck:function(row,$element){
                    Controller.api.bindevent();
                    selectedValue= $("#table").bootstrapTable('getSelections');  
                    console.log(selectedValue);
                },
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // Fast.config.openArea = ['50%','50%'];
            //绑定TAB事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                // var options = table.bootstrapTable(tableOptions);
                var typeStr = $(this).attr("href").replace('#', '');
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    params.kind = typeStr;
                    return params;
                };
                table.bootstrapTable('refresh', {});
                current_kind = typeStr;
                if (typeStr == 'all') {
                    $('.btn-add').addClass('hide')
                } else {
                    $('.btn-add').removeClass('hide')
                }

                // 重新初始化表格参数
                Table.api.init({
                    extend: {
                        index_url: 'exam/tiku/index' + location.search,
                        add_url: 'exam/tiku/add?kind=' + current_kind,
                        edit_url: 'exam/tiku/edit?kind=' + current_kind,
                        del_url: 'exam/tiku/del_all',
                        multi_url: 'exam/tiku/multi',
                        import_url: 'exam/tiku/import',
                        table: 'cate',
                    }
                });

                return false;
            });
        },

        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'exam/tiku/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'exam/tiku/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'exam/tiku/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
                
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();

            setTimeout(function () {
                $("#c-kind").trigger("change");
            }, 100);
        },
        edit: function () {
            Controller.api.bindevent();
            $("#c-kind").trigger('change')
        },
        api: {
            bindevent: function () {
                $(document).on("change", "#c-kind", function () {
                    $("#c-parent_id option[data-type='all']").prop("selected", true);
                    $("#c-parent_id option").removeClass("hide");

                    // 隐藏非当前kind的数据
                    $("#c-parent_id option[data-type!='" + $(this).val() + "']").addClass("hide");
                    // 编辑时隐藏当前数据
                    let id = $('#id').val()
                    
                    if (id) {
                        $("#c-parent_id option[value='" + id + "']").addClass("hide");
                    }
                    $("#c-parent_id option[value='0']").removeClass("hide");

                    // 刷新select项
                    $("#c-parent_id").data("selectpicker") && $("#c-parent_id").selectpicker("refresh");

                    // 可用群体
                    var kind = $(this).val();
                    if (kind === 'QUESTION') {
                        $(".uses").removeClass("hide");
                    } else {
                        $(".uses").addClass("hide");
                    }
                });

                Form.api.bindevent($("form[role=form]"));

                $(document).on("change", "#c-parent_id", function () {
                    console.log('parent_id', $(this).val())
                });

                $(document).on('click', '#c-school-ids', function() {
                    var schoolIds = $('input[name="row[school_ids]').val();
                    var schoolNames = $('#c-school-ids').val();
                    //focus获取焦点时执行方法，也可以blur,click等
                    Fast.api.open('classes/school/index?is_select=1&limit=20&schoolIds='+schoolIds+'&schoolName='+schoolNames, __('SELECT_TITLE'),{
                        //接收传过来的参数
                        callback:function(value){
                            console.log('返回值',value)
                            //在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
                            $('#c-school-ids').val(value.getSchoolNames.join(','));
                            $('input[name="row[school_ids]"]').val(value.ids.join(','))
                        }
                    });
                })

                
            }
        }
    };
    return Controller;
});
